package com.luyun.frogpay.view.home;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Build;
import android.text.InputFilter;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.android.arouter.utils.TextUtils;
import com.google.android.material.snackbar.Snackbar;
import com.luyun.frogpay.R;
import com.luyun.frogpay.base.baseclass.ActivityManager;
import com.luyun.frogpay.base.baseclass.BaseActivity;
import com.luyun.frogpay.base.routepath.RouteActivityPath;
import com.luyun.frogpay.pojo.KqwSpeechCompound;
import com.luyun.frogpay.view.facepay.FacePayResultActivity;
import com.luyun.frogpay.base.utils.EditInputFilter;
import com.luyun.frogpay.widget.WxfacePayLoadingDialog;
import com.tencent.wxpayface.WxPayFace;

import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = RouteActivityPath.HOME_ACTIVITY)
public class HomeActivity extends BaseActivity<HomePresenter> implements HomeContract.IHomeView {

    @BindView(R.id.tv_payment_amount)
    EditText tvPaymentAmount;
    @BindView(R.id.tv_scan_pay)
    TextView tvScanPay;

    @BindView(R.id.tv_face_pay)
    TextView tvFacePay;
    @BindView(R.id.phto1)
    ImageView phto1;
    @BindView(R.id.phto2)
    ImageView phto2;
    @BindView(R.id.add)
    TextView add;
    @BindView(R.id.liner)
    RelativeLayout liner;
    @BindView(R.id.recy)
    LinearLayout recy;

    /**
     * 当前页面显示的付款金额
     */
    private StringBuffer sbPayment;

    /**
     * 微信支付加载弹窗
     */
    private WxfacePayLoadingDialog wxfacePayLoadingDialog;
    public static final int IDLE = 932;
    public static final int CODE_SCANING = 480;
    public static final int FACE_SCANING = 652;
    public int currentStatus = IDLE;
    private KqwSpeechCompound kqwSpeechCompound;
    private double total;
    ObjectAnimator objectAnimator = new ObjectAnimator();

    @Override
    protected void initView() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        ActivityManager.getInstance().addActivity(this);
        wxfacePayLoadingDialog = new WxfacePayLoadingDialog(this);
        tvPaymentAmountAddListener();
        if (!Build.MODEL.equals("TZH-L1")) presenter.initHeart();
       // presenter.initHeart();
        sbPayment = new StringBuffer();
        InputFilter[] filters = {new EditInputFilter()};
        tvPaymentAmount.setFilters(filters);

        kqwSpeechCompound = new KqwSpeechCompound(this);
        startArrowMove();
        phto1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Snackbar.make(v, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();

            }
        });

    }


    private void tvPaymentAmountAddListener() {
//        tvPaymentAmount.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
//                Log.d("tvPaymentAmount  beforeTextChanged:  " + charSequence.toString());
//            }
//
//            @Override
//            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
//                String currentPayment = tvPaymentAmount.getText().toString();
//
//            }
//
//            @Override
//            public void afterTextChanged(Editable editable) {
//                Log.d("tvPaymentAmount  afterTextChanged:  " + editable.toString());
//            }
//        });
    }

    @Override
    protected void initInjector() {
        activityComponent.inject(this);
    }

    @Override
    protected int getLayoutId() {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏
        return R.layout.activity_home;

    }

    @OnClick({R.id.tv_scan_pay, R.id.tv_face_pay})
    public void onClick(View v) {
        total = TextUtils.isEmpty(tvPaymentAmount.getText().toString()) ? 0 : Double.valueOf(tvPaymentAmount.getText().toString());
        switch (v.getId()) {
            default:
                break;
            case R.id.tv_scan_pay:
                if (total <= 0) {

                    kqwSpeechCompound.speaking("请输入正确的付款金额");
                    return;
                }
                if (currentStatus == IDLE) {
                    presenter.startCodeScanner();
                    kqwSpeechCompound.speaking("请扫码支付"+total+"元  ");
                } else if (currentStatus == CODE_SCANING) {
                    presenter.stopCodeScanner();
                }
                break;
            case R.id.tv_face_pay:
                if (total <= 0) {
                    kqwSpeechCompound.speaking("请输入正确的付款金额");
                }else if (total>=3000){
                    Toast.makeText(HomeActivity.this,"单笔支付金额不能超过3000元",Toast.LENGTH_SHORT).show();
                }else {
                    presenter.getWxfacepayRawdata();
                }
                break;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        //playVideo(true);
        presenter.currentStatus = IDLE;
        tvPaymentAmount.requestFocus();
        tvPaymentAmount.setCursorVisible(false);//不显示光标

    }

    @Override
    protected void onStop() {
        super.onStop();
        //playVideo(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //刷脸支付 SDK　释放资源
        WxPayFace.getInstance().releaseWxpayface(context);
       // phto1.clearAnimation();
       // phto2.clearAnimation();
    }

    /**
     * 播放视频
     */
    public void playVideo(boolean isPlay) {
       /* String uri = "android.resource://" + getPackageName() + "/" + R.raw.home_video;
        vvGuide.setVideoURI(Uri.parse(uri));
        vvGuide.setOnCompletionListener((mediaPlayer) -> vvGuide.start());
        if (isPlay) {
            vvGuide.start();
        } else {
            vvGuide.stopPlayback();
        }*/
    }

    @Override
    public void isSshowWeChatLoadingDialog(boolean isShow) {
        if (isShow) {
            wxfacePayLoadingDialog.show();
        } else {
            wxfacePayLoadingDialog.hide();
        }
    }

    /**
     * {@link FacePayResultActivity}
     *
     * @param isSuccess
     */
    @Override
    public void facePayResult(boolean isSuccess) {
        Double total = TextUtils.isEmpty(tvPaymentAmount.getText().toString()) ? 0 : Double.valueOf(tvPaymentAmount.getText().toString());
        ARouter.getInstance()
                .build(RouteActivityPath.FACE_PAY_RESULT_ACTIVITY)
                .withDouble("Totals", total)
                .withBoolean("isFacePaySuccess", isSuccess)
                .navigation();
        presenter.stopCodeScanner();
        total=0.00;
        tvPaymentAmount.setText("￥0.00");
        Log.i("adgaxa", total + "");
    }

    @Override
    public String getTotalStr() {
        String yuanStr = tvPaymentAmount.getText().toString().trim();
        double yuan = Double.valueOf(yuanStr);
        DecimalFormat decimalFormat = new DecimalFormat("##########.##");
        return decimalFormat.format(yuan * 100);
    }

    @Override
    public void setCurrentStatus(int status) {
        currentStatus = status;
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        Log.i("adgaxa", event.getKeyCode() + "");
        total = TextUtils.isEmpty(tvPaymentAmount.getText().toString()) ? 0 : Double.valueOf(tvPaymentAmount.getText().toString());

        if (event.getKeyCode() == KeyEvent.KEYCODE_NUMPAD_ADD) {
            if (total <= 0) {
                kqwSpeechCompound.speaking("请输入正确的付款金额");
            } else {
                presenter.startCodeScanner();
                kqwSpeechCompound.speaking("请扫码支付"+total+"元  ");

            }
        }


        if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
            if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                if (total <= 0) {
                    kqwSpeechCompound.speaking("请输入正确的付款金额");
                }else if (total>=3000){
                    Toast.makeText(HomeActivity.this,"单笔支付金额不能超过3000元",Toast.LENGTH_SHORT).show();
                }else {
                    kqwSpeechCompound.speaking("请刷脸支付"+total+"元");
                    presenter.getWxfacepayRawdata();
                }

            }

        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }



    /**
     * 开始平移动画
     */
    private void startArrowMove() {


        //方式一:直接换算运动距离，因为高度已经限定
        //向上平移的距离计算，等于2倍运动区域高度+自身的高度
       /* float moveDistance = 660 * getResources().getDisplayMetrics().density;
        //生成一个平移动画对象,记得向上运动是负数
        Animation moveUpAnimation = new TranslateAnimation(0, 0, 0, -moveDistance);
        moveUpAnimation.setDuration(3000);//3秒运动完一次循环
        moveUpAnimation.setRepeatCount(Animation.INFINITE); //无限循环
        moveUpAnimation.setInterpolator(new LinearInterpolator()); //匀速运动
        //开始视图动画
        phto1.startAnimation(moveUpAnimation);
        phto2.startAnimation(moveUpAnimation);*/

            //方式二:代码计算运动距离，一定要等布局完成后才能开始动画
            phto1.post(new Runnable() {
                @Override
                public void run() {
                    //向上平移的距离计算，等于2倍运动区域高度+自身的高度
                    float moveDistance = recy.getHeight()*2 + phto1.getHeight();
                    //生成一个平移动画对象,记得向上运动是负数
                    Animation moveUpAnimation = new TranslateAnimation(0,0,60,-60);
                    moveUpAnimation.setDuration(1500);//3秒运动完一次循环
                    moveUpAnimation.setRepeatCount(Animation.INFINITE); //无限循环
                    moveUpAnimation.setInterpolator(new LinearInterpolator()); //匀速运动
                    //开始视图动画
                    phto1.startAnimation(moveUpAnimation);
//                    //生成一个平移动画对象,记得向上运动是负数
                    /*Animation moveUpAnimation2 = new TranslateAnimation(0,0,-60,60);
                    moveUpAnimation.setDuration(3000);//3秒运动完一次循环
                    moveUpAnimation.setRepeatCount(Animation.ABSOLUTE); //无限循环
                    moveUpAnimation.setInterpolator(new LinearInterpolator()); //匀速运动
                    moveUpAnimation.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            phto1.startAnimation(moveUpAnimation2);
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                    moveUpAnimation2.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            phto1.startAnimation(moveUpAnimation);
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });*/
                }
            });
    }

}
